package com.kakarote.oa.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.common.log.annotation.OperateLog;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.entity.OperationResult;
import com.kakarote.common.log.enums.ApplyEnum;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.common.log.enums.OperateObjectEnum;
import com.kakarote.common.log.enums.OperateTypeEnum;
import com.kakarote.core.common.Result;
import com.kakarote.core.common.cache.CrmCacheKey;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.servlet.LoginFromCookie;
import com.kakarote.core.utils.BaseUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.oa.entity.BO.OaPrintTemplateQueryBO;
import com.kakarote.oa.entity.PO.OaExaminePrintTemplate;
import com.kakarote.oa.entity.VO.OaExaminePrintFieldVO;
import com.kakarote.oa.service.IOaExaminePrintTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;

/**
 * @author wwl
 * @date 2022/7/14 18:32
 */
@RestController
@RequestMapping("/oaExaminePrintTemplate")
@Slf4j
@Api(tags = "办公审批打印模板")
public class OaExaminePrintTemplateController {

    @Autowired
    private IOaExaminePrintTemplateService oaExaminePrintTemplateService;

    /**
     * 修改审批时调用本接口
     *
     * @param newCategoryId a
     * @param oldCategoryId a
     * @return a
     */
    @ApiOperation("修改打印模板的审批模板id")
    @PostMapping("/updateCategoryId")
    public Result<Boolean> updateCategoryId(@RequestParam("newCategoryId") Long newCategoryId, @RequestParam("oldCategoryId") Long oldCategoryId) {
        return Result.ok(oaExaminePrintTemplateService.updateCategoryId(newCategoryId, oldCategoryId));
    }

    @ApiOperation("查询打印模板列表")
    @PostMapping("/queryList")
    public Result<BasePage<OaExaminePrintTemplate>> queryList(@RequestBody OaPrintTemplateQueryBO printTemplateBO) {
        BasePage<OaExaminePrintTemplate> adminPrintTemplateBasePage = oaExaminePrintTemplateService.queryList(printTemplateBO);
        return Result.ok(adminPrintTemplateBasePage);
    }

    @ApiOperation("新增模板")
    @PostMapping("/add")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.SAVE, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.EXAMINE_PRINT_TEMPLATE)
    public Result addPrintTemplate(@RequestBody OaExaminePrintTemplate template) {
        template.setUpdateTime(LocalDateTimeUtil.now());
        oaExaminePrintTemplateService.save(template);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationInfo("新建审批打印模板：" + template.getTemplateName());
        operationLog.setOperationObject(template.getTemplateName());
        return OperationResult.ok(operationLog);
    }

    @ApiOperation("修改模板")
    @PostMapping("/update")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.UPDATE, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.EXAMINE_PRINT_TEMPLATE)
    public Result updatePrintTemplate(@RequestBody OaExaminePrintTemplate adminPrintTemplate) {

        oaExaminePrintTemplateService.updateById(adminPrintTemplate);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationInfo("编辑审批打印模板：" + adminPrintTemplate.getTemplateName());
        operationLog.setOperationObject(adminPrintTemplate.getTemplateName());
        return OperationResult.ok(operationLog);
    }

    @ApiOperation("跟进ID查询打印模板")
    @PostMapping("/queryById")
    public Result<OaExaminePrintTemplate> queryPrintTemplateById(@RequestParam("templateId") Long templateId) {
        OaExaminePrintTemplate byId = oaExaminePrintTemplateService.getById(templateId);
        return Result.ok(byId);
    }

    @ApiOperation("删除模板")
    @PostMapping("/delete")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.DELETE, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.EXAMINE_PRINT_TEMPLATE)
    public Result deletePrintTemplate(@RequestParam("templateId") Long templateId) {
        OaExaminePrintTemplate template = oaExaminePrintTemplateService.getById(templateId);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationInfo("删除审批打印模板：" + template.getTemplateName());
        operationLog.setOperationObject(template.getTemplateName());

        oaExaminePrintTemplateService.deletePrintTemplate(templateId);
        return OperationResult.ok(operationLog);
    }

    @ApiOperation("查询字段")
    @PostMapping("/queryFields")
    public Result<OaExaminePrintFieldVO> queryFields(@RequestParam("templateId") Long templateId) {
        OaExaminePrintFieldVO voList = oaExaminePrintTemplateService.queryFields(templateId);
        return Result.ok(voList);
    }

    @ApiOperation("打印")
    @PostMapping("/print")
    public Result<String> print(@RequestParam("templateId") Long templateId, @RequestParam("id") Long id) {
        String print = oaExaminePrintTemplateService.print(templateId, id);
        return Result.ok(print);
    }

    @ApiOperation("预览")
    @PostMapping("/preview")
    public Result<String> preview(@RequestParam("content") String content, @RequestParam("type") String type) {
        String s = oaExaminePrintTemplateService.preview(content, type);
        return Result.ok(s);
    }

    @ApiOperation("下载文件")
    @RequestMapping("/down")
    @LoginFromCookie
    public void down(@RequestParam("type") Integer type, @RequestParam("key") String key, HttpServletResponse response) {
        String object = BaseUtil.getRedis().get(CrmCacheKey.CRM_PRINT_TEMPLATE_CACHE_KEY + key);
        if (StrUtil.isNotEmpty(object)) {
            JSONObject parse = JSON.parseObject(object);
            String path;
            int two = 2;
            if (type == two) {
                path = parse.getString("word");
            } else {
                path = parse.getString("pdf");
            }
            if (FileUtil.exist(path)) {
                ServletUtil.write(response, FileUtil.file(path));
                return;
            }
        }
        ServletUtil.write(response, Result.ok().toJSONString(), "text/plain");
    }

    @ApiOperation("iframe")
    @RequestMapping("/preview.pdf")
    @LoginFromCookie
    public void preview(String key, HttpServletResponse response) {
        String object = BaseUtil.getRedis().get(CrmCacheKey.CRM_PRINT_TEMPLATE_CACHE_KEY + key);
        if (StrUtil.isNotEmpty(object)) {
            JSONObject parse = JSON.parseObject(object);
            String path = parse.getString("pdf");
            if (FileUtil.exist(path)) {
                File file = FileUtil.file(path);
                BufferedInputStream in = null;
                ServletOutputStream out = null;
                try {
                    in = FileUtil.getInputStream(file);
                    response.setContentType("application/pdf");
                    IoUtil.copy(in, response.getOutputStream());
                } catch (Exception ex) {
                    log.error("导出错误", ex);
                } finally {
                    IoUtil.close(in);
                    IoUtil.close(out);
                }
                return;
            }
        }
        ServletUtil.write(response, Result.ok().toJSONString(), "text/plain");
    }

    @ApiOperation("复制模板")
    @PostMapping("/copyTemplate")
    @OperateLog(apply = ApplyEnum.OFFICE_MANAGEMENT, behavior = BehaviorEnum.COPY, type = OperateTypeEnum.SETTING, object = OperateObjectEnum.EXAMINE_PRINT_TEMPLATE)
    public Result copyTemplate(@RequestParam("templateId") Long templateId) {
        OperationLog operationLog = oaExaminePrintTemplateService.copyTemplate(templateId);
        return OperationResult.ok(operationLog);
    }

}
